package lxy.contacttest;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.List;

import lxy.contacttest.utils.ContactBean;
import lxy.contacttest.utils.PhoneContactUtils;

public class ContactListActivity extends AppCompatActivity {
    private static final int REQUEST_ADD = 100;
    // 联系人适配器
    private ContactsAdapter mAdapter;
    private ListView listview;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_list);
        listview = (ListView) findViewById(R.id.list_view);
        mAdapter = new ContactsAdapter(this);
        listview.setAdapter(mAdapter);

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                request();
            }
        });
        //去详情
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(ContactListActivity.this, ContactDetailActivity.class);
                intent.putExtra("contact_id", mAdapter.getItem(position).getContact_id());
                intent.putExtra("name", mAdapter.getItem(position).getName());
                startActivityForResult(intent, REQUEST_ADD);
            }
        });
        //添加
        findViewById(R.id.btn_bottom).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ContactListActivity.this, ContactAddActivity.class);
                startActivityForResult(intent, REQUEST_ADD);
            }
        });
    }

    /**
     * 请求数据
     */
    private void request() {
        List<ContactBean> infos = PhoneContactUtils.getContactList(this);
        mAdapter.clear();
        mAdapter.addAllItem(infos);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            if (requestCode == REQUEST_ADD) {
                request();
            }
        }
    }
}
